package huaweiod.first;

import java.util.Scanner;

/**
 * 华为OD机试真题 Java 实现【机器人】【100%通过率】【2022.11 Q4 新题】
 * 4 4
 * 1 2 5 2
 * 2 4 4 5
 * 3 5 7 1
 * 4 6 2 4
 * 6
 */
public class A_2023_56_Robot {

    public static int[][] dist = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int row = in.nextInt();
        int col = in.nextInt();
        int[][] matrix = new int[row][col];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = in.nextInt();
            }
        }
        int ans = 0;
        for (int i = 0; i < matrix.length; i++) {
            boolean[][] path = new boolean[row][col];
            for (int j = 0; j < matrix[i].length; j++) {
                int bfs = bfs(matrix, path, i, j);
                ans = Math.max(ans, bfs);
            }
        }
        System.out.println(ans);
    }

    public static int bfs(int[][] matrix, boolean[][] path, int x, int y) {
        path[x][y] = true;
        int count = 1;
        // 4个方向
        for (int i = 0; i < dist.length; i++) {
            int newX = x + dist[i][0];
            int newY = y + dist[i][1];
            if (newX < matrix.length && newX >= 0 && newY < matrix[0].length && newY >= 0
                    && Math.abs(matrix[x][y] - matrix[newX][newY]) <= 1 && !path[newX][newY]) {
                path[newX][newY] = true;
                count += bfs(matrix, path, newX, newY);
            }
        }
        return count;
    }
}
